package com.mooc.http;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class HttpResponse {
    private int statusCode;
    private String contentType="text/plain;charset=UTF-8";
    private SocketChannel socketChannel;
    public HttpResponse(SocketChannel socketChannel){
        this.socketChannel=socketChannel;
    }
    public void write(String resData){
        try {
            write(resData.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
    public void write(byte[] data){
        try {
            StringBuilder sb = new StringBuilder();
            sb.append("HTTP/1.1 "+statusCode+" "+CodeStatus.getCodeDesc(statusCode)+"\r\n");
            sb.append("Content-Type:"+ contentType +"\r\n");
            sb.append("Content-Length: " + data.length);
            sb.append("\r\n\r\n");
            String head = sb.toString();
            ByteBuffer byteBuffer = ByteBuffer.allocate(head.getBytes().length + data.length);
            byteBuffer.clear();
            byteBuffer.put(head.getBytes("utf-8"));
            byteBuffer.put(data);
            byteBuffer.flip();
            while (byteBuffer.hasRemaining()) {
                socketChannel.write(byteBuffer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public String getContentType() {
        return contentType;
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

}
